<template>
  <view class="index-container">
    <!-- 来电浮层（优先级最高） -->
    <view v-if="incomingCall.show" class="incoming-call-overlay">
      <view class="incoming-card">
        <text class="caller-number">{{ incomingCall.fromPhone }} 正在呼叫您（号码：{{ incomingCall.toPhone }}）</text>
        <view class="call-actions">
          <button class="refuse-btn" @click="rejectCall">挂断</button>
          <button class="accept-btn" @click="acceptCall">接听</button>
        </view>
      </view>
    </view>

    <!-- 余额卡片 -->
    <view class="balance-card">
      <view class="balance-info">
        <view class="balance-text">
          <text class="balance-label">当前余额</text>
          <text class="balance-amount">¥{{ balance.toFixed(2) }}</text>
        </view>
        <button class="recharge-btn" @click="goToRecharge">充值</button>
      </view>
    </view>
    
    <!-- 快捷功能 -->
    <view class="functions">
      <view class="function-item" @click="goToNumbers">
        <view class="function-icon">
          <image src="/static/icons/rental.png" mode="widthFix"></image>
        </view>
        <text>号码租赁</text>
      </view>
      <view class="function-item" @click="goToCall('')">
        <view class="function-icon">
          <image src="/static/icons/dial.png" mode="widthFix"></image>
        </view>
        <text>拨号通话</text>
      </view>
      <view class="function-item" @click="goToBills">
        <view class="function-icon">
          <image src="/static/icons/records.png" mode="widthFix"></image>
        </view>
        <text>通话记录</text>
      </view>
      <view class="function-item" @click="goToRecharge">
        <view class="function-icon">
          <image src="/static/icons/topup.png" mode="widthFix"></image>
        </view>
        <text>话费充值</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onUnmounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
// 引入电话列表API（与电话页面共用）
import { phoneApi } from '../../api/phoneApi';

// 存储所有绑定号码的WebSocket连接（格式：[{ phone: '18464866848', conn: WebSocket实例 }, ...]）
const wsConnections = ref([]);
// 用户绑定的所有电话号码列表
const userPhoneList = ref([]);
// 来电信息：记录呼叫方、被呼叫的号码
const incomingCall = ref({
  show: false,
  fromPhone: '',
  toPhone: '' // 存储当前被呼叫的具体号码（如18464866848）
});

const userInfo = ref({});
const balance = ref(100.50);

onLoad(async () => {
  await fetchUserInfo();
  await loadUserPhoneList();
  // 为所有绑定号码初始化WebSocket连接
  initAllWsConnections();
});

onUnmounted(() => {
  // 页面销毁时关闭所有WebSocket连接，避免内存泄漏
  closeAllWsConnections();
});

/**
 * 加载用户绑定的电话号码列表
 */
const loadUserPhoneList = async () => {
  try {
    uni.showLoading({ title: '加载绑定号码中...' });
    const userId = userInfo.value?.userId;
    if (!userId) {
      console.warn('用户ID为空，无法加载绑定号码');
      uni.hideLoading();
      return;
    }
    // 调用API获取当前用户的所有绑定号码
    const res = await phoneApi.getPhoneList(userId);
    
    if (res.code === 0 && Array.isArray(res.data)) {
      userPhoneList.value = res.data;
      console.log('当前用户绑定的电话号码列表：', JSON.stringify(userPhoneList.value, null, 2));
    } else {
      uni.showToast({ title: '加载绑定号码失败', icon: 'none' });
    }
  } catch (error) {
    console.error('加载绑定号码失败:', error);
    uni.showToast({ title: error.message || '网络异常', icon: 'none' });
  } finally {
    uni.hideLoading();
  }
};

/**
 * 为所有绑定号码初始化WebSocket连接
 * 每个号码对应一个独立连接，确保任意号码被呼叫都能接收
 */
const initAllWsConnections = () => {
  // 先关闭已有连接，避免重复创建
  closeAllWsConnections();
  wsConnections.value = [];

  // 循环遍历所有绑定号码，创建WebSocket连接
  userPhoneList.value.forEach(phoneItem => {
    const phone = phoneItem.phoneNumber;
    // 拼接当前号码的WebSocket连接地址
    const wsuri = `ws://localhost:6008/phone-client/websocket/call/${phone}`;
    const conn = new WebSocket(wsuri);

    // 连接成功：将连接实例存入数组
    conn.onopen = () => {
      console.log(`号码 [${phone}] WebSocket 连接成功`);
      wsConnections.value.push({ phone, conn });
    };

    // 统一消息处理：所有连接的"call"消息都触发来电浮层
    conn.onmessage = (res) => {
      console.log(`号码 [${phone}] 收到消息：`, res.data);
      try {
        const data = JSON.parse(res.data);
        // 仅处理"call"类型消息，且确保被呼叫号码匹配当前连接的号码
        if (data.type === 'call' && data.to === phone) {
          incomingCall.value = {
            show: true,
            fromPhone: data.from, // 呼叫方号码
            toPhone: phone // 当前被呼叫的号码
          };
        }
      } catch (e) {
        console.error(`号码 [${phone}] 解析消息失败：`, e);
      }
    };

    // 连接错误：打印错误日志
    conn.onerror = (err) => {
      console.error(`号码 [${phone}] WebSocket 错误：`, err);
    };

    // 连接关闭：从数组中移除该连接
    conn.onclose = () => {
      console.log(`号码 [${phone}] WebSocket 连接关闭`);
      wsConnections.value = wsConnections.value.filter(item => item.phone !== phone);
    };
  });
};

/**
 * 关闭所有绑定号码的WebSocket连接
 */
const closeAllWsConnections = () => {
  wsConnections.value.forEach(item => {
    const { phone, conn } = item;
    // 仅关闭处于"打开"状态的连接
    if (conn && conn.readyState === WebSocket.OPEN) {
      conn.close();
      console.log(`号码 [${phone}] WebSocket 主动关闭`);
    }
  });
  // 清空连接数组
  wsConnections.value = [];
};

/**
 * 接听来电：跳转到通话页，传递正确的号码参数
 */
const acceptCall = () => {
  const { fromPhone, toPhone } = incomingCall.value;
  // 关键：myPhone传递"被呼叫的号码"（toPhone），确保通话页连接正确的WebSocket
  uni.navigateTo({
    url: `/pages/calling/index?myPhone=${toPhone}&fromPhone=${fromPhone}&isIncoming=true`
  });
  // 隐藏来电浮层
  incomingCall.value.show = false;
};

/**
 * 拒绝来电：从被呼叫的号码发送hangup消息给呼叫方
 */
const rejectCall = () => {
  const { fromPhone, toPhone } = incomingCall.value;
  // 找到被呼叫号码对应的WebSocket连接
  const targetConn = wsConnections.value.find(item => item.phone === toPhone);

  if (targetConn && targetConn.conn.readyState === WebSocket.OPEN) {
    const hangupMsg = JSON.stringify({
      type: 'hangup',
      from: toPhone, // 从被呼叫的号码发送（确保消息来源正确）
      to: fromPhone, // 发送给呼叫方
      userId: userInfo.value.userId || '',
      userType: userInfo.value.userType || '公客',
      time: new Date().getTime()
    });
    targetConn.conn.send(hangupMsg);
    console.log('发送挂断消息：', hangupMsg);
  } else {
    console.warn(`号码 [${toPhone}] 连接未就绪，无法发送挂断消息`);
  }

  // 隐藏来电浮层
  incomingCall.value.show = false;
};

/**
 * 获取用户信息（包含userId、userType、余额等）
 */
const fetchUserInfo = async () => {
  try {
    // 从缓存读取登录状态和用户信息
    const isLogin = uni.getStorageSync('isLogin');
    const storedUser = uni.getStorageSync('userInfo');
    
    if (!isLogin || !storedUser?.userId) {
      // 未登录：跳转到登录页
      uni.navigateTo({ url: '/pages/login/login' });
      return;
    }

    // 调用API获取最新用户信息（含余额）
    const res = await uni.request({
      url: 'http://localhost:6006/user-client/api/loginInfo/getUserInfo',
      method: 'POST',
      data: { userId: storedUser.userId },
      header: { 'Content-Type': 'application/x-www-form-urlencoded' }
    });

    if (res.data.code === 0) {
      userInfo.value = res.data.data;
      // 更新用户余额
      balance.value = res.data.data?.readyAmount || 0;
    } else {
      uni.showToast({ title: '获取用户信息失败', icon: 'none' });
    }
  } catch (error) {
    console.error('获取用户信息失败：', error);
    uni.showToast({ title: '网络异常', icon: 'none' });
  }
};

/**
 * 页面跳转函数
 */
const goToRecharge = () => uni.navigateTo({ url: '/pages/recharge/recharge' });
const goToNumbers = () => uni.navigateTo({ url: '/pages/numbers/numbers' });
const goToBills = () => uni.navigateTo({ url: '/pages/bills/bills' });
const goToCall = (number) => {
  // 公客用户余额低于15元：拦截拨号，提示充值
  if (userInfo.value.userType === '公客' && balance.value < 15) {
    uni.showModal({
      title: '余额不足',
      content: '您的余额低于15元，请充值后进行通话',
      showCancel: false,
      confirmText: '去充值',
      success: (res) => res.confirm && goToRecharge()
    });
    return;
  }
  // 跳转到拨号页，传递默认号码（可选）
  uni.navigateTo({
    url: `/pages/call/call?virtualNumber=${encodeURIComponent(number || '')}`
  });
};
</script>

<style scoped>
/* 来电浮层：全屏遮罩，居中显示来电卡片 */
.incoming-call-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.7);
  z-index: 9999; /* 确保优先级最高，覆盖其他内容 */
  display: flex;
  align-items: center;
  justify-content: center;
}
.incoming-card {
  width: 80%;
  background-color: #fff;
  border-radius: 20rpx;
  padding: 50rpx 30rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.15);
}
.caller-number {
  font-size: 36rpx;
  margin-bottom: 60rpx;
  color: #333;
  font-weight: bold;
  text-align: center; /* 确保长文本换行后居中 */
  line-height: 50rpx;
}
.call-actions {
  display: flex;
  justify-content: space-around;
  width: 100%;
  max-width: 400rpx; /* 限制按钮区域宽度，避免过宽 */
}
.refuse-btn, .accept-btn {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  line-height: normal;
  border: none;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}
.accept-btn {
  background-color: #4cd964;
  color: #fff;
}
.refuse-btn {
  background-color: #ff3b30;
  color: #fff;
}

/* 首页整体样式 */
.index-container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 120rpx; /* 底部留白，避免内容被导航栏遮挡 */
}
/* 余额卡片样式 */
.balance-card {
  background: linear-gradient(135deg, #007AFF, #0051AA);
  padding: 30rpx;
  border-radius: 16rpx;
  margin: 20rpx;
  color: #fff;
  position: relative;
  box-shadow: 0 4rpx 16rpx rgba(0, 122, 255, 0.2);
}
.balance-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.balance-text {
  display: flex;
  flex-direction: column;
}
.balance-label {
  font-size: 28rpx;
  opacity: 0.9;
  margin-bottom: 8rpx;
}
.balance-amount {
  font-size: 48rpx;
  font-weight: bold;
  display: block;
}
.recharge-btn {
  background-color: rgba(255, 255, 255, 0.2);
  color: #fff;
  border-radius: 20rpx;
  padding: 0 20rpx;
  height: 60rpx;
  line-height: 60rpx;
  font-size: 28rpx;
  border: none;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}
/* 快捷功能区样式 */
.functions {
  display: flex;
  flex-wrap: wrap;
  background-color: #fff;
  border-radius: 16rpx;
  margin: 20rpx;
  padding: 20rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
}
.function-item {
  width: 25%;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx 0;
  cursor: pointer;
}
.function-icon {
  width: 80rpx;
  height: 80rpx;
  background-color: #f0f7ff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 15rpx;
}
.function-icon image {
  width: 40rpx;
  height: 40rpx;
}
.function-item text {
  font-size: 26rpx;
  color: #333;
}
</style>